package com.smartcommunity.base.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
/**
 * @ClassName: ScheduleConfig
 * @Description: 定时任务异步执行配置
 * @author: minsheng
 * @Date: 2019/1/15 14:35
 * @Company:
 * @version V1.5.0
 */
@Configuration
public class ScheduleConfig implements SchedulingConfigurer, AsyncConfigurer {

	/**
     * 多线程配置
     * @return ThreadPoolTaskScheduler
     */
	@Bean(destroyMethod = "shutdown")
	public ThreadPoolTaskScheduler taskScheduler() {
		ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
		scheduler.setPoolSize(50);
		// 设置线程名前缀
		scheduler.setThreadNamePrefix("job-");
		// 线程内容执行完后60秒自动请求关闭
		scheduler.setAwaitTerminationSeconds(60);
		scheduler.setWaitForTasksToCompleteOnShutdown(true);
		return scheduler;
	}

	/**
     * 异步任务
     * @return Executor
     */
	@Override
	public Executor getAsyncExecutor() {
		Executor executor = taskScheduler();
		return executor;
	}

	/**
     * 异常处理
     * @return AsyncUncaughtExceptionHandler
     */
	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new SimpleAsyncUncaughtExceptionHandler();
	}

	/**
     * 并行任务
     * @param scheduledTaskRegistrar
     */
	@Override
	public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
		TaskScheduler taskScheduler = taskScheduler();
		scheduledTaskRegistrar.setTaskScheduler(taskScheduler);

	}

}
